//
//  OauthViewController.swift
//  WB
//
//  Created by leador on 17/4/2.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        loadWebView()
    }
    
}

extension OauthViewController {
    
    func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"返回", style: .plain, target: self, action: #selector(OauthViewController.backClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title:"填充", style: .plain, target: self, action: #selector(OauthViewController.fillClick))
        
    }
    
    
    func loadWebView() {

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(app_url)"
        
        guard let url = URL(string:urlString) else {
            return
        }
        
        let request = URLRequest(url:url)
        
        webView.loadRequest(request)
        
    }
    
    
}

extension OauthViewController {
    
    func backClick() {
        dismiss(animated: true, completion: nil)
    }
    
    func fillClick() {
        
        let jsString = "document.getElementById('userId').value=15701173915;document.getElementById('passwd').value='Yuanman806'"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
}

extension OauthViewController:UIWebViewDelegate {
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        guard let url = request.url else {
            return true
        }
        
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else {
            return true
        }
        
        let stringArr = urlString.components(separatedBy: "code=")
        
        guard let code = stringArr.last else {
            return true
        }
        
        //请求token
        loadToken(code: code)
        
        return true
    }
    
}

extension OauthViewController {
    
    func loadToken(code:String) {
        
        NetworkTools.shareInstance.loadAccessToken(code: code) { (account)
            
            in
            
            guard let accountStr = account.access_token else {
                return
            }
            
            guard let uidStr = account.uid else {
                return
            }
            
            NetworkTools.shareInstance.loadUserInfo(accessToken: accountStr, uid: uidStr, finished: { (result, error) in
            
                if error != nil {
                    return
                }
                
                account.name = result?["name"] as! String?
                account.avatar_hd = result?["avatar_hd"] as! String?
                
                //保存account对象(归档)
                NSKeyedArchiver.archiveRootObject(account, toFile:UserAccountViewModel.shareInstance.accountPath)
                
                UserAccountViewModel.shareInstance.account = account
                
                self.dismiss(animated: false, completion: {

                    UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
                    
                })

            })
            
        }
        
    }
    
}
